package com.ruoyi.sevenInterfaces.utils;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.config.DbInterfaceConfig;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.http.Http2Utils;
import com.ruoyi.sevenInterfaces.domain.vo.ReqVo;
import com.ruoyi.sevenInterfaces.domain.vo.ResVo;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description TODO
 * @Author wsl
 * @Date 2025-02-20 21:31
 * @Version 1.0
 */

public class HttpUtil {


    public static  Object getBean(DbInterfaceConfig config, ReqVo reqVo, Class clazz) {
        getNewReqVo(reqVo);
        String result = Http2Utils.doPost(config.getBaseUrl(), JSON.toJSONString(reqVo));
        ResVo resVo =  JSON.parseObject(result, ResVo.class);
        if(resVo.getCode() == HttpStatus.SUCCESS){
            return BeanUtil.toBean(resVo.getData().get(0), clazz);
        } else {
            //暂时抛异常
            throw new ServiceException("调用失败:" + resVo);
        }
    }

    public static  Object getListBean(DbInterfaceConfig config, ReqVo reqVo, Class clazz) {
        getNewReqVo(reqVo);
        String result = Http2Utils.doPost(config.getBaseUrl(), JSON.toJSONString(reqVo));
        ResVo resVo =  JSON.parseObject(result,ResVo.class);
        if(resVo.getCode() == HttpStatus.SUCCESS){
            List<Object> data1 = resVo.getData();
            return data1.stream().map(o -> BeanUtil.toBean(o, clazz)).collect(Collectors.toList());
        } else {
            //暂时抛异常
            throw new ServiceException("调用失败:" + resVo);
        }
    }



    private static  void getNewReqVo(ReqVo reqVo){
        //增加其他参数：比如token、userId
        //reqVo.set
    }

    public static  Object create(DbInterfaceConfig config,ReqVo reqVo) {
        getNewReqVo(reqVo);
        String result = Http2Utils.doPost(config.getBaseUrl()+config.getCreate(), JSON.toJSONString(reqVo));
        ResVo resVo = JSON.parseObject(result, ResVo.class);
        if(resVo.getCode() != HttpStatus.SUCCESS){
            //暂时抛异常
            throw new ServiceException("调用失败:" + resVo);
        }
        return resVo;
    }

}
